//
//  WBNetwoekManager.swift
//  Weibo
//
//  Created by kobe on 2016/12/24.
//  Copyright © 2016年 kobe. All rights reserved.
//

import UIKit
import AFNetworking

//Swift的枚举支持任意数据类型
enum WBHTTPMethod {
    case GET
    case POST
}

//网络管理工具
class WBNetworkManager: AFHTTPSessionManager {

    //静态区 / 常量 
    static let shared:WBNetworkManager = {
        //实例化对象
       let instance = WBNetworkManager()
        
        //设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    //用户账户的懒加载
    lazy var userAccount = WBUserAccount()
    
    // 用户登录标记
    var userLogin:Bool {
        return userAccount.access_token != nil
    }
    
    // 专门负责token的网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET,URLString:String,parameters:[String:Any]?,completion: @escaping ((_:Any?,_:Bool) -> ())) {
        
        //处理json字典
        // 0>判断token是否为空
        guard let token = userAccount.access_token else {
            
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            completion(nil, false)
            print("没有登录")
            return
        }
        
        // 1>判断参数字典是否存在 如果为nil
        var parameters = parameters
        
        if parameters == nil {
            parameters = [String:Any]()
            
        }
        // 2>设置参数字典
        parameters!["access_token"] = token
        
        // 调用request发起真正的网络请求方法
        request(URLString: URLString, parameters: parameters, completion: completion)
    }
    
    
    /// 封装 AFN 的 GET / POST 请求
    ///
    /// - parameter method:     GET / POST`
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数
    /// - parameter completion: 完成回调(json,isSuccess)
    func request(method:WBHTTPMethod = .GET,URLString:String,parameters:[String:Any]?,completion: @escaping ((_:Any?,_:Bool) -> ())) {
        
        let success = { (task:URLSessionDataTask,json:Any?)->() in
            completion(json,true)
        }
        let failure = { (task:URLSessionDataTask?,error:Error)->() in
            
            //针对403错误
            if (task?.response as?HTTPURLResponse)?.statusCode == 403 {
                print("token过期")
                
                // 发送通知(本方法不知道被谁调用,谁接收到通知谁处理)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")
                
            }
            
            
            
            print("网络请求错误 \(error)")
            completion(nil,false)
        }
        
        
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
